#! /usr/bin/env node
let process = require("process")
let fs = require("fs")
let shellCode = "";
let main = (args) => {
    let helpStr = `
    luapkg 帮助
    {配置文件} 使用配置文件
    init {名称} 初始化工程
    build
        {lua文件} 编译当前lua文件,默认为win32
        {target1,target2} 指定编译为标平台： win32 win64 linux macos ios android (目前只有win32)  
    bundle {lua文件} 根据lua依赖打包为单个lua文件,并打成bytecode
    `
    if (!args[0]) {
        console.warn(helpStr);
    } else {
        switch (args[0]) {
            case "bundle":
                break
            case "init":
                if (!fs.existsSync(`.vscode`)) fs.mkdirSync(".vscode");
                let settings = {
                    "lua.debug.settings.luaVersion": "jit",
                    "Lua.runtime.version": "LuaJIT",
                    "files.encoding": "gb2312",
                    "lua.debug.settings.sourceCoding": "ansi",
                    "Lua.runtime.fileEncoding": "ansi",
                    "Lua.completion.callSnippet": "Both"
                }
                let jsonCode =
                {
                    // See https://go.microsoft.com/fwlink/?LinkId=733558
                    // for the documentation about the tasks.json format
                    "version": "2.0.0",
                    "tasks": [
                        {
                            "label": "编译为exe",
                            "type": "shell",
                            "command": "luapkg build \${file}",
                            "problemMatcher": [],
                            "group": {
                                "kind": "build",
                            }
                        },
                        {
                            "label": "编译为exe并upx?",
                            "type": "shell",
                            "command": "luapkg build \${file}",
                            "problemMatcher": [],
                            "group": {
                                "kind": "build",
                            }
                        }
                    ]
                }

                if (!fs.existsSync(`.vscode/settings.json`)) fs.writeFileSync(`.vscode/settings.json`, JSON.stringify(settings, null, "\t"));
                if (!fs.existsSync(`.vscode/tasks.json`)) fs.writeFileSync(`.vscode/tasks.json`, JSON.stringify(jsonCode, null, "\t"));
                if (!fs.existsSync(`main.lua`)) fs.writeFileSync(`main.lua`, `print("helloworld")`, { encoding: "ascii" });
                let pkgObj = {
                    "target": "win32",
                    "ico": "",
                    "version": "",
                    "output": ""
                }
                if (!fs.existsSync(`pkg.json`)) fs.writeFileSync(`pkg.json`, JSON.stringify(pkgObj, null, "\t"));
                break;
            case "build":
                if (!args[1]) return console.error("没有指定要编译的文件");
                const PE = require('pe-library');
                const ResEdit = require('resedit');
                const fileData = fs.readFileSync(`${__dirname.replace("/", "\\")}\\platform\\win32\\luajit.exe`)
                let exe = PE.NtExecutable.from(fileData);
                let res = PE.NtExecutableResource.from(exe);
                let codePaser = require("./codePaser")
                let dependFile = {};
                codePaser.dependFile(args[1], null, dependFile);
                let main = dependFile[args[1]];
                delete dependFile[args[1]];
                let str = "";
                for (const path in dependFile) {
                    let content = dependFile[path];
                    str += `
                    package.loaded["${path}"] = (function ()
                        ${content}
                    end)()
                    `
                }
                str += main;
                res.replaceResourceEntryFromString(10, "_", "chinese", str);
                res.outputResource(exe);
                let newBinary = exe.generate();
                fs.writeFileSync('win32.exe', Buffer.from(newBinary));
                if (args.slice(2).indexOf("upx") >= 0) {
                    shellCode = `${__dirname.replace("/", "\\")}\\platform\\upx.exe win32.exe`
                }
                console.warn("已经生成exe在当前目录")
                //let iconFile = ResEdit.Data.IconFile.from(fs.readFileSync('MyIcon.ico'));

                // -- replace version
                // console.log(res.entries);
                // let viList = ResEdit.Resource.VersionInfo.fromEntries(res.entries);
                // let vi = viList[0];
                // // setFileVersion will set `vi.fixedInfo.fileVersionMS`/`fileVersionLS` and 'FileVersion' string value
                // // ('1033' means 'en-US')
                // vi.setFileVersion(1, 0, 0, 0, 1033);
                // // ('lang: 1033' means 'en-US', 'codepage: 1200' is the default codepage)
                // vi.setStringValues(
                //     { lang: 1033, codepage: 1200 },
                //     {
                //         FileDescription: 'My application',
                //         ProductName: 'My product',
                //     }
                // );
                // vi.outputToResourceEntries(res.entries);

                // // write to another binary

                break;
            default:
                break;
        }
    }

}


main(process.argv.slice(2));
fs.writeFileSync(`${__dirname.replace("/", "\\")}\\temp.cmd`, shellCode);